<?php
/**
 * Created by PhpStorm.
 * User: dolia
 * Date: 15/12/26
 * Time: 下午3:34
 */

namespace App\Repositories;
use App\Interfaces\CartService;
use App\Repositories\DiscountRepository;
use App\Models\Cart;
use App\Models\CartShop;
use App\Models\Category;
use App\Models\Goods;
use App\Models\Picture;
use App\Exceptions\Interfaces\CartServiceException;
use App\Models\Shop;
use DB,Log;
use Illuminate\Database\Eloquent\Collection;

class CartRepository implements  CartService
{

    /**
     * 会话类型  SESSION|USER
     * @var
     */
    protected $type;

    /**
     * 购物车回话ID
     * @var
     */
    protected  $reference_id;


    public function __construct($type,$reference_id){

        $this->init($type, $reference_id);


    }

    public function init($type,$reference_id){

        if (!in_array($type,['SESSION','USER']))
        {
            throw new CartServiceException("type参数类型错误,必须为SESSION或USER,");
        }

        $this->type = $type;

        $this->reference_id = $reference_id;

    }

    private function getTypeFiled(){

        if ($this->type=='SESSION') $filed = 'session_id';
        if ($this->type=='USER') $filed = 'user_id';
        return $filed;
    }


    /**
     * 获取购物车商品
     * @param string $userId
     * @param string $session_id
     * @return mixed
     */
    public function getCartGoods(){
        $cart = Cart::join('goods','cart.goods_id','=','goods.goods_id')
            ->where('cart.'.$this->getTypeFiled(),$this->reference_id)
            ->get();

        foreach ($cart as $key => $value) {

            if ($value->goods_thumb) {

                $mobile_goods_thumb = Picture::find($value->goods_thumb)->url;

                $cart[$key]->mobile_goods_thumb = $mobile_goods_thumb;
            }
        }

         return $cart;

    }

    /**
     * 添加商品到购物车
     * @param $goods_id
     * @param $goods_number
     * @return mixed
     */
    public function addGoods($goods_id,$goods_num){

        $goods = Goods::find($goods_id);

        if($goods){
            $goods_number = $goods->goods_number;
            $is_on_sale = $goods->is_on_sale;

            if($is_on_sale!=1){
                throw new CartServiceException('商品【'.$goods->goods_name."】已下架");
            }//end if()

            if($goods_number<$goods_num){

                throw new CartServiceException('商品【'.$goods->goods_name."】库存不足");
            }//end if()

            //判断该会话购物车是否已经有该产品
            $cartGoods = Cart::where($this->getTypeFiled(), $this->reference_id)->where('goods_id', $goods_id)->get();
            $is_exit = $cartGoods->count();

            if($is_exit){
                $total_num = (integer)($cartGoods[0]->buy_num + $goods_num);
                //如果有则更新数量
                $cart = Cart::where($this->getTypeFiled(), $this->reference_id)->where('goods_id', $goods_id)->update(['goods_id'=>$goods_id, 'buy_num'=>$total_num]);     //如果有更新返回1，如果数据没变返回0
            }else{

                //如果没有则插入一条新纪录
                $cart = Cart::insert([$this->getTypeFiled()=>$this->reference_id, 'goods_id'=>$goods_id, 'buy_num'=>$goods_num]);       //成功返回true
            }//end if()

        }else{
            throw new CartServiceException('商品【'.$goods->goods_name."】不存在或已删除");
        }//end if()

        return $cart;

    }//end func addGoods



    public function updateNumber($goods_id,$buy_num){


            $goods = Cart::join('goods','goods.goods_id','=','cart.goods_id')->where('cart.goods_id',$goods_id)->where($this->getTypeFiled(),$this->reference_id)->first();
            if ($goods){

                if($goods->is_on_sale!=1){

                    throw new CartServiceException("该商品已下架");
                }//end if()

                if($goods->goods_number<$buy_num){

                    throw new CartServiceException("该商品库存不足");
                }//end if()


                $goods->buy_num = $buy_num;

                $goods->save();
            }

        return true;

    }


    /**
     * 删除购物车中商品
     * @param $goods_ids ：商品id数组
     * @return mixed
     */
    public function removeGoods(Array $goods_ids){

        if($goods_ids){

            foreach ($goods_ids as $key=>$goods_id) {

                $cart = Cart::where($this->getTypeFiled(), $this->reference_id)->where('goods_id', $goods_id)->delete();

            }//end foreach()

        }else{

            throw new CartServiceException("要删除的商品数组不能为空");
        }//end if()


    }//end func removeGoods

    /**
     * 删除购物车中的商品，
     * @apiParam Array goods  商品id及购买数量的数组，如：goods = array(0=>array('goods_id'=>1346, 'buy_num'=>1), 1=>array('goods_id'=>1343, 'buy_num'=>1)).
     * @return [type]        [description]
     */
    public function removeCartGoods(Array $goods)
    {
        if ($goods) {

            foreach ($goods as $key => $value) {

                $cart = Cart::where($this->getTypeFiled(), $this->reference_id)->where('goods_id', $value['goods_id'])->first();

                if ($cart) {
                    if ($cart->buy_num-$value['buy_num']>0) {

                        $cart->update(['buy_num'=>$cart->buy_num-$value['buy_num']]);
                    }else{

                        $cart->delete();
                    }
                }
            }
        }
    }



    /**
     * 获取购物车商品总数、总价、总关税等信息
     * @param array $goods_id
     * @return mixed 1. 总价,总个数,总关税
     */

    //public function getInfo(Array $goods_id){
    public function getInfo(){


        $cartGoods = Cart::select('goods_id','buy_num')->where($this->getTypeFiled(),$this->reference_id)->get()->toArray();

        return $this->getGoodsInfo($cartGoods);


    }//end func getInfo

    /**
     * 获取商品数组中商品总数、总价、总关税等信息
     * @param array $cartGoods :已选中商品数组array(0=>array('goods_id'=>1, 'buy_num'=>2), 1=>array('goods_id'=>2, 'goods_num'=>2))
     * @return mixed 1. 总价,总个数,总关税
     */
    public function getGoodsInfo($cartGoods){

        $cartGoods = $this->fillterCartGoods($cartGoods);


        $goodsIds = array_keys($cartGoods);//拆出商品ID


        $cartGoodsObj = Cart::select('goods_id','cart_id')
            ->whereIn('goods_id',$goodsIds)
            ->where($this->getTypeFiled(),$this->reference_id)
            ->get();


        $cartIds = $cartGoodsObj->lists('cart_id');//拆出cart_id



        //$shopIds = Goods::whereIn('goods_id',$goodsIds)->groupBy('shop_id')->lists('shop_id');//查询商品表查出店铺id

        //$shops = Shop::whereIn('id',$shopIds)->get();//获取店铺实体

        $info['total_number'] = 0;
        $info['total_number_not'] = 0;
        $info['total_price'] = 0.00;
        $info['total_tariff_price'] = 0.00;
        $info['total_discount_price'] = 0.00;
        $info['pay_price'] = 0.00;

        //查询该商铺下跨境贸易商品
        $eshopGoods = Goods::join('cart','cart.goods_id','=','goods.goods_id')//关联购物车
            ->join('category','category.cat_id','=','goods.cat_id')//关联分类
            ->whereIn('cart.cart_id',$cartIds)//查询给定的商品
            ->where('goods.type',1)//E贸易条件
            ->get();

        foreach ($eshopGoods as $key => $value) {

            /*$excise_duty_percent = intval($value->excise_duty_percent);//消费税

            $value_added_tax_percent = intval($value->value_added_tax_percent);//增值税*/

            /*$excise_duty_percent = intval(empty($value->recode_excise_duty_percent) ? $value->excise_duty_percent : $value->recode_excise_duty_percent);//消费税率

            $value_added_tax_percent = intval(empty($value->recode_value_added_tax_percent) ? $value->value_added_tax_percent : $value->recode_value_added_tax_percent);//增值税率*/

            if ($value->recode_excise_duty_percent == 0) {

                $excise_duty_percent = 0;
            }elseif ($value->recode_excise_duty_percent > 0) {

                $excise_duty_percent = $value->recode_excise_duty_percent;
            }elseif ($value->recode_excise_duty_percent < 0) {

                $excise_duty_percent = $value->excise_duty_percent;
            }else{

                $excise_duty_percent = $value->excise_duty_percent;
            }

            $excise_tax = 0.00;

            if ($excise_duty_percent) {

                /**
                 * 消费税=（完税价格+关税）/（1-消费税率）*消费税率*70%=1/(1-0.15）*0.15*0.7=0.123529
                 * 增值税=（完税价格+关税+消费税）*0.17*0.7=（1+0+0.17647）*0.17*0.7=0.13999
                 * （注：完税价格为固定值1，关税为固定值0）
                 *
                 * 含消费税的综合税率=消费税+增值税=0.123529+0.13999=0.263519=0.2635
                 * 不含消费税的综合税率=0.119
                 *
                 * 注：计算增值税时，消费税要全额计算，不是0.7之后的消费税
                 *
                 * 商品的综合税率 = 消费税 + 增值税；
                 * 商品的税金 = 商品价格 * 商品数量 * 综合税率。（订单中产生的关税）
                 */
                $excise_tax = 1 / (1 - $excise_duty_percent / 100) * $excise_duty_percent / 100 * 70 / 100;                 //消费税
            }

                $value_added_tax = (1 + 0 + $excise_tax * 100 / 70) * 17 / 100 * 70 / 100;         //增值税

                $consolidated_tax = $excise_tax + $value_added_tax;                                             //综合税

            if ($value->goods_real_price && $value->goods_real_price>0) {

                // $tariff_price = $value->goods_real_price*$cartGoods[$value->goods_id]*($excise_duty_percent/100+$value_added_tax_percent/100)*70/100;

                $tariff_price = $value->goods_real_price*$cartGoods[$value->goods_id]*$consolidated_tax;
            }else{

                // $tariff_price = $value->shop_price*$cartGoods[$value->goods_id]*($excise_duty_percent/100+$value_added_tax_percent/100)*70/100;

                $tariff_price = $value->shop_price*$cartGoods[$value->goods_id]*$consolidated_tax;
            }

            $eshopGoods[$key]['tariff_price'] = sprintf("%.2f",substr(sprintf("%.3f", $tariff_price), 0, -1));
        }

        $eshopGoods = $this->calculateGoods($eshopGoods,$cartGoods);
        $info['total_number'] += $eshopGoods['total_number'];
        $info['total_number_not'] += $eshopGoods['total_number_not'];
        $info['total_price'] += $eshopGoods['total_price'];
        $info['total_tariff_price'] += $eshopGoods['total_tariff_price'];
        $info['total_discount_price'] += $eshopGoods['total_discount_price'];
        $info['pay_price'] += $eshopGoods['pay_price'];


        //查询该商铺下普通贸易商品
        $cshopGoods = Goods::join('cart','cart.goods_id','=','goods.goods_id')//关联购物车
        ->join('category','category.cat_id','=','goods.cat_id')//关联分类
        ->whereIn('cart.cart_id',$cartIds)//查询给定的商品
        ->where('goods.type',0)//普通贸易条件
        ->get();

        foreach ($cshopGoods as $key => $value) {

            $cshopGoods[$key]['tariff_price'] = '';
        }
        $cshopGoods = $this->calculateGoods($cshopGoods,$cartGoods);

        $info['total_number'] += $cshopGoods['total_number'];
        $info['total_number_not'] += $cshopGoods['total_number_not'];
        $info['total_price'] += $cshopGoods['total_price'];
        $info['total_tariff_price'] += $cshopGoods['total_tariff_price'];
        $info['total_discount_price'] += $cshopGoods['total_discount_price'];
        $info['pay_price'] += $cshopGoods['pay_price'];

        $info['eshopGoods'] = $eshopGoods;
        $info['cshopGoods'] = $cshopGoods;
        return $info;

    }//end func getGoodsInfo


    public function getCartNumber(){

        //$this->getInfo();

        $cartGoods = Cart::select(DB::raw('count(buy_num) as number'))->where($this->getTypeFiled(),$this->reference_id)->first();

        return intval($cartGoods->number);


    }

    private function calculateGoods($shopGoods,$cartGoods){

        $discountRepository = new DiscountRepository();

        $total_number = 0;
        $total_number_not = 0;      //下架、删除、无库存等商品的数量
        $total_price = 0;
        $total_tariff_price = 0;
        $calculate['total_discount_price'] = 0.00;        //限时折扣总金额
        $discount_total_number = 0;                       //使用限时折扣商品的数量

        /*foreach ($shopGoods as $k=>$goods) {

            //将所有的商品可用的最大折扣信息加入到商品里面

            $goods['discount'] = [];
            $goods['goods_real_price'] = [];        //商品折扣后的单价
            $goods['goods_discount_price'] = [];    //商品折扣的总金额

            $discount = $discountRepository->getCanUseBiggestDiscountByGoodsId($goods->goods_id);

            if ($discount) {

                $goods['discount'] = $discount->toArray();

                $goods['goods_real_price'] = sprintf("%.2f",sprintf("%.3f", $goods->shop_price * intval($goods['discount']['discount_value']) / 100));

                $goods['goods_discount_price'] = sprintf("%.2f",sprintf("%.3f",$goods['goods_real_price'] * intval($cartGoods[$goods->goods_id])));
            }
        }*/

        foreach ($shopGoods as $goods) {

            $goods_real_price = 0.00;       //商品折扣后的价格

            $excise_tax = 0.00;

            $value_added_tax = 0.00;

            if ($goods->type==1){
                //$tariff_percent = $goods->tariff_percent;

                /*$excise_duty_percent = intval($goods->excise_duty_percent);//消费税

                $value_added_tax_percent = intval($goods->value_added_tax_percent);//增值税*/

                /*$excise_duty_percent = intval(empty($goods->recode_excise_duty_percent) ? $goods->excise_duty_percent : $goods->recode_excise_duty_percent);//消费税

                $value_added_tax_percent = intval(empty($goods->recode_value_added_tax_percent) ? $goods->value_added_tax_percent : $goods->recode_value_added_tax_percent);//增值税*/

                if ($goods->recode_excise_duty_percent == 0) {

                    $excise_duty_percent = 0;
                }elseif ($goods->recode_excise_duty_percent > 0) {

                    $excise_duty_percent = $goods->recode_excise_duty_percent;
                }elseif ($goods->recode_excise_duty_percent < 0) {

                    $excise_duty_percent = $goods->excise_duty_percent;
                }else{

                    $excise_duty_percent = $goods->excise_duty_percent;
                }

                if ($excise_duty_percent) {

                    /**
                     * 消费税=（完税价格+关税）/（1-消费税率）*消费税率*70%=1/(1-0.15）*0.15*0.7=0.123529
                     * 增值税=（完税价格+关税+消费税）*0.17*0.7=（1+0+0.17647）*0.17*0.7=0.13999
                     * （注：完税价格为固定值1，关税为固定值0）
                     *
                     * 含消费税的综合税率=消费税+增值税=0.123529+0.13999=0.263519=0.2635
                     * 不含消费税的综合税率=0.119
                     *
                     * 注：计算增值税时，消费税要全额计算，不是0.7之后的消费税
                     *
                     * 商品的综合税率 = 消费税 + 增值税；
                     * 商品的税金 = 商品价格 * 商品数量 * 综合税率。（订单中产生的关税）
                     */
                    $excise_tax = 1 / (1 - $excise_duty_percent / 100) * $excise_duty_percent / 100 * 70 / 100;                 //消费税
                }

                $value_added_tax = (1 + 0 + $excise_tax * 100 / 70) * 17 / 100 * 70 / 100;         //增值税

                if (isset($goods['discount']) && $goods['discount']) {

                    // $eDiscountPrice = $goods->shop_price * intval(100 - $goods['discount']['discount_value']) / 100 * $cartGoods[$goods->goods_id];

                    // $eDiscountPrice = sprintf("%.2f",substr(sprintf("%.3f", $eDiscountPrice), 0, -1));
                    $eDiscountPrice = sprintf("%.2f",substr(sprintf("%.3f", ($goods->shop_price - $goods->goods_real_price) * $cartGoods[$goods->goods_id]), 0, -1));

                    // $goods_real_price = sprintf("%.2f",substr(sprintf("%.3f", $goods->shop_price * intval($goods['discount']['discount_value']) / 100), 0, -1));

                    $goods_real_price = $goods->goods_real_price;

                    $calculate['total_discount_price'] += $eDiscountPrice;

                    $discount_total_number += $cartGoods[$goods->goods_id];
                }else{

                    $goods_real_price = $goods->shop_price;
                }
            }else{
                //$tariff_percent = 0;

                $excise_duty_percent=0;

                $value_added_tax_percent=0;

                if (isset($goods['discount']) && $goods['discount']) {


                    // $cDiscountPrice = $goods->shop_price * intval(100 - $goods['discount']['discount_value']) / 100 * $cartGoods[$goods->goods_id];

                    // $cDiscountPrice = sprintf("%.2f",substr(sprintf("%.3f", $cDiscountPrice), 0, -1));
                    $cDiscountPrice = sprintf("%.2f",substr(sprintf("%.3f", ($goods->shop_price - $goods->goods_real_price) * $cartGoods[$goods->goods_id]), 0, -1));

                    // $goods_real_price = sprintf("%.2f",substr(sprintf("%.3f", $goods->shop_price * intval($goods['discount']['discount_value']) / 100), 0, -1));

                    $goods_real_price = $goods->goods_real_price;

                    $calculate['total_discount_price'] += $cDiscountPrice;

                    $discount_total_number += $cartGoods[$goods->goods_id];
                }else{

                    $goods_real_price = $goods->shop_price;
                }
            }

            //计算商品总数
            $total_number += $cartGoods[$goods->goods_id];

            if($goods->is_on_sale != 1 || $goods->goods_number<1 || !empty($goods->deleted_at)){
                $total_number_not++;      //下架、删除、无库存等商品的数量
                continue;
            }

            //计算总价
            $total_price += $goods->shop_price * $cartGoods[$goods->goods_id];

            $consolidated_tax = $excise_tax + $value_added_tax;                                             //综合税

            //计算总关税
            // $total_tariff_price += $goods_real_price*$cartGoods[$goods->goods_id]*($excise_duty_percent/100+$value_added_tax_percent/100)*70/100;

            $total_tariff_price += $goods_real_price*$cartGoods[$goods->goods_id]*$consolidated_tax;

        }//end foreach()

        $calculate['total_number'] = (integer)$total_number;
        $calculate['total_number_not'] = (integer)$total_number_not;
        $calculate['total_price'] = sprintf("%.2f",substr(sprintf("%.3f", $total_price), 0, -1));
        $calculate['total_tariff_price'] = sprintf("%.2f",substr(sprintf("%.3f", $total_tariff_price), 0, -1));
        $calculate['shopGoods'] = $shopGoods;
        $calculate['pay_price'] = $calculate['total_price']+$calculate['total_tariff_price']-$calculate['total_discount_price'];
        $calculate['total_discount_price'] = sprintf("%.2f",substr(sprintf("%.3f", $calculate['total_discount_price']), 0, -1));

        return $calculate;
    }


    /**
     * 游客用户转化为登陆用户
     * @param $session_id
     * @param $user_id
     * @return mixed
     */
    public function linkSessionToUser($session_id,$user_id){

        if ($session_id!==''&&$user_id!=''){

            $sessionGoods = Cart::where('session_id',$session_id)->where('user_id',0)->get();
            foreach($sessionGoods as $goods){

                $cartGoods = Cart::where('user_id',$user_id)->where('goods_id',$goods->goods_id)->first();

                //如果购物车中存在该商品
                if ($cartGoods){

                    $goods->delete();
                    $cartGoods->buy_num = $cartGoods->buy_num+$goods->buy_num;
                    $cartGoods->save();

                }else{

                    $goods->update(['user_id'=>$user_id,'session_id'=>'']);

                }
            }

        }

    }//end func linkSessionToUser


    /**
     * 过滤购物车参数
     * @param $cartGoods
     * @return \Illuminate\Support\Collection
     */
    private function fillterCartGoods($cartGoods){

        //取出该用户的所有购买商品ID
        $cartIds = Cart::select('goods_id')->where($this->getTypeFiled(),$this->reference_id)->get()->lists('goods_id')->toArray();

        $fillterCartGoods = [];

        foreach($cartGoods as $k=>$v){

            if (in_array($v['goods_id'],$cartIds)){//判断传来的goods_id参数是否在购物车

                $fillterCartGoods[$v['goods_id']]=$v['buy_num'];

            }
        }

        return $fillterCartGoods;
    }


}//end class